#include <iostream>
#include <cstring>

//c
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>

int main() {
    /*
        客户端和服务端使用 socket (fd) 进行信息交换
            client            |          server
           c_socket         <--->       s_socket
            c_addr            |          s_addr
                              |        bind(s_socket, s_addr) listen(s_socket) //被动接收
    连接:
    connect(c_socket, s_addr)--->      accept(s_socket, out: c_addr) --> acceptfd

    信息交换:
        write(c_socket)      --->       read(accept_fd)
        read(c_socket)       <---       write(accept_fd)
    */

    int socketfd = socket(AF_INET, SOCK_STREAM, 0);
    if (socketfd == -1)
        return -1;
    
    sockaddr_in addrIn;
    addrIn.sin_family = AF_INET;
    inet_pton(AF_INET, "0.0.0.0", &addrIn.sin_addr);
    addrIn.sin_port = htons(SERT_PORT);

    //客户端连接
    if (connect(socketfd, (sockaddr*)(&addrIn), sizeof(sockaddr_in)) == -1) {
        std::cout << "connect error" << std::endl;
        return -1;
    }

    char sendMsg[MAXLINE + 1] = {0};
    //cin.get 会获取MAXLINE 数量的字符, 再加一个 \0
    std::cin.get(sendMsg, MAXLINE + 1); 
    if (write(socketfd, sendMsg, MAXLINE) == -1) {
        std::cout << "write error!" << std::endl;
        return -1;
    }
        
    if (read(socketfd, sendMsg, MAXLINE) != 0) 
        std::cout << socketfd << ": " << sendMsg << std::endl;

    close(socketfd);

    return 0;
}